<template>
  <div>
    <el-form
      ref="editFormRef"
      :rules="rules"
      :model="editForm.data"
      label-width="120"
    >
      <el-form-item label="真实姓名" prop="realName">
        <el-input
          v-model="editForm.data.realName"
          style="width: 320px"
          minlength="2"
          maxlength="10"
          placeholder="请输入真实姓名"
        />
      </el-form-item>
      <el-form-item label="登录账号" prop="userName">
        <el-input
          v-model="editForm.data.userName"
          style="width: 320px"
          placeholder="请输入登录账号"
          disabled
        />
      </el-form-item>
      <el-form-item label="手机号码" prop="phone">
        <el-input
          v-model="editForm.data.phone"
          style="width: 320px"
          maxlength="11"
          placeholder="请输入手机号码"
        />
      </el-form-item>
      <el-form-item label="电子邮箱">
        <el-input
          v-model="editForm.data.email"
          placeholder="请输入电子邮箱"
          style="width: 320px"
        />
      </el-form-item>
      <el-form-item label="所属部门" prop="deptId">
        <el-tree-select
          v-if="department.data.length"
          v-model="editForm.data.deptId"
          :data="department.data"
          :props="defaultProps"
          :render-after-expand="false"
          check-strictly
          style="width: 320px"
          placeholder="请选择所属部门"
          :default-expanded-keys="[editForm.data.deptId]"
        />
      </el-form-item>
      <el-form-item label="角色">
        <el-cascader
          v-model="editForm.data.roleIds"
          :options="roleList.data"
          style="width: 320px"
          placeholder="请选择角色"
          :props="{
            value: 'id',
            label: 'name',
            multiple: true,
          }"
          @change="handleCascaderChange"
          clearable
        />
      </el-form-item>
      <el-form-item>
        <div class="footer">
          <div></div>
          <div>
            <el-button class="reset-btn" @click="resetForm(editFormRef)"
              >取 消</el-button
            >
            <el-button class="confirm-btn" @click="submitForm(editFormRef)"
              >确 认</el-button
            >
          </div>
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { reactive, ref } from "vue";
import {
  getDepartment,
  getRole,
  getEditCashier,
} from "../request.js";

const props = defineProps({
  operationId: String,
});
console.log("props ===>", props.operationId);

const department = reactive({
  data: [],
});

const editForm = reactive({
  data: {
    userId: props.operationId.userId,
    realName: props.operationId.realName,
    userName: props.operationId.userName,
    phone: props.operationId.phone,
    email: props.operationId.email,
    deptId: props.operationId.deptId,
    roleIds: props.operationId.roleIds,
  },
});

const handleCascaderChange = (value) => {
  console.log("value ===>", value);
  editForm.data.roleIds = editForm.data.roleIds
    .filter((item) => Array.isArray(item)) // 确保是数组
    .map((item) => item[0]);
  console.log("value ===>", editForm.data.roleIds);
};

const defaultProps = {
  children: "nodes",
  label: "name",
  value: "id",
};

const getDepartmentData = async () => {
  await getDepartment().then((res) => {
    // console.log("res ===>", res);
    department.data = res.data.result;
    // const transformedData = res.data.result.map((dept) => {
    //   return {
    //     ...dept,
    //     deptId: dept.id, // 添加一个与 id 属性值相同的 deptId 属性
    //     nodes: dept.nodes.map((subDept) => {
    //       return {
    //         ...subDept,
    //         deptId: subDept.id, // 为子部门也添加一个 deptId 属性
    //         nodes: subDept.nodes.map((subSubDept) => {
    //           return {
    //             ...subSubDept,
    //             deptId: subSubDept.id, // 为子子部门也添加一个 deptId 属性
    //           };
    //         }),
    //       };
    //     }),
    //   };
    // });
    // department.data = transformedData;
    // console.log("department.data ===>", department.data);
  });
};
getDepartmentData();

const roleList = reactive({
  data: [],
});

const getRoleData = async () => {
  await getRole().then((res) => {
    console.log("res ===>", res);
    roleList.data = res.data.result;

    // props.operationId.roleIds.forEach((sectionId) => {
      
    //   const section = roleList.data.find(
    //     (item) => item.id === parseInt(sectionId)
    //   );

    //   if (section) {
    //     // console.log("section ===>", section);
    //     editForm.data.roleIds.push(parseInt(sectionId));
    //   }
    // });
  });
};

getRoleData();

const editFormRef = ref("");

const rules = reactive({
  realName: [
    {
      required: true,
      message: "请输入真实姓名",
      trigger: "blur",
    },
    {
      min: 2,
      max: 10,
      message: "长度在 2 到 10 个字符",
      trigger: "blur",
    },
  ],
  userName: [
    {
      required: true,
      message: "请输入登录账号",
      trigger: "blur",
    },
  ],
  phone: [
    {
      required: true,
      message: "请输入手机号码",
      trigger: "change",
    },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "手机号码格式不正确，请重新输入",
      trigger: "blur",
    },
  ],
  deptId: [
    {
      required: true,
      message: "请选择所属部门",
      trigger: "change",
    },
  ],
});

const submitForm = (formEl) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      // console.log("submit!");
      getEditCashier(editForm.data).then((res) => {
        // console.log("res ===>", res);
        if (res.data.code === 0) {
          ElMessage({
            type: "success",
            message: res.data.result,
          });
          emits("operationDone");
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    }
  });
};

const resetForm = (formEl) => {
  if (!formEl) return;
  editForm.data = {};
  formEl.resetFields();
  emits("operationDone");
};

const emits = defineEmits(["operationDone"]);
</script>

<style lang="less" scoped>
.footer {
  width: 100%;
  display: flex;
  justify-content: space-between;
}
.reset-btn {
  width: 65px;
  height: 32px;
  background: #ffffff;
  border-radius: 2px;
  border: 1px solid #d9d9d9;
  font-weight: 400;
  font-size: 14px;
  color: rgba(0, 0, 0, 0.65);
}
.confirm-btn {
  width: 65px;
  height: 32px;
  background: #007aff;
  border-radius: 2px;
  font-weight: 400;
  font-size: 14px;
  color: #ffffff;
}
</style>